package com.arpa.wms.controller;

import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.consts.TipConst;
import com.arpa.wms.domain.dto.CountingDTO;
import com.arpa.wms.domain.dto.InventoryDTO;
import com.arpa.wms.domain.entity.Counting;
import com.arpa.wms.domain.enums.CountingStatusEnum;
import com.arpa.wms.domain.vo.CountingVO;
import com.arpa.wms.domain.vo.InventoryVO;
import com.arpa.wms.service.ICountingService;
import com.arpa.wms.service.IInventoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 盘点单 controller
 * @author jinss
 * @date 2020-08-28 13:26:01
 **/
@Api(tags = "盘点管理")
@RestController
@RequestMapping(value="/counting", produces = "application/json;charset=UTF-8")
@Log4j2
public class CountingController {

   @Autowired
   private ICountingService countingService;

   @Autowired
   private IInventoryService inventoryService;

    /**
     * 获取 盘点单 列表
     * @param countingDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "WMS盘点管理列表数据", notes = "用于WMS盘点管理列表页面加载数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = CountingVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(CountingDTO countingDTO, HttpServletRequest request) {
        try {
            //校验授权仓库code和货主code不能为空
            Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            //登录账号授权的仓库过滤
            countingDTO.setWarehouseCodes(authMap.get(CommonConst.WAREHOUSE_CODES));
            //登录账号授权的货主过滤
//            countingDTO.setShipmentCodes(UserUtil.getAuthorizeShipmentCodes());

            countingDTO.setGroupCode(UserUtil.getBranchCode());

            CountingVO countingVO = countingService.queryListSum(countingDTO);
            List<CountingVO> countingList = countingService.queryList(countingDTO);


            Page returnPage = new Page(countingDTO.getPageNum(), countingDTO.getPageSize());
            returnPage.setRecords(countingList);
            returnPage.setTotal(countingVO.getTotal());
            returnPage.setSumObject(countingVO);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 盘点单
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 盘点单 ", notes = "添加 盘点单 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@RequestBody @Validated(Counting.Save.class) Counting entity, HttpServletRequest request) {
        try {
            entity.setGroupCode(UserUtil.getBranchCode());
            countingService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改 盘点单
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "修改 盘点单", notes = "修改 盘点单")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@RequestBody @Validated(Counting.Update.class) Counting entity, HttpServletRequest request) {
        if(StrUtil.isBlank(entity.getCode())){
            return Result.error(TipConst.CODE_NOT_EMPTY);
        }
        //判断当前盘点单状态，只有新建状态能修改
        int count = countingService.count(new QueryWrapper<Counting>().lambda().eq(Counting::getCode,entity.getCode()).eq(Counting::getStatus, CountingStatusEnum.NEW.getValue()).eq(Counting::getGroupCode,UserUtil.getBranchCode()));
        if(count==0){
            return Result.error("盘点单【"+entity.getCode()+"】状态已改变不能修改" );
        }
        boolean update = countingService.updateByCode(entity);
        if(update){
            return Result.ok("盘点单【"+entity.getCode()+"】更新成功");
        }else{
            return Result.error("盘点单【"+entity.getCode()+"】更新失败");
        }
    }

    /**
     * 提交 盘点单
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "提交 盘点单", notes = "提交 盘点单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping(value = "/submit")
    public Result submit(@RequestBody Counting entity, HttpServletRequest request) {

        //判断当前盘点单状态，只有新建状态能修改
        if(StrUtil.isNotBlank(entity.getCode())) {
            int count = countingService.count(new QueryWrapper<Counting>().lambda().eq(Counting::getCode, entity.getCode()).eq(Counting::getGroupCode,UserUtil.getBranchCode()).eq(Counting::getStatus, CountingStatusEnum.NEW.getValue()));
            if (count == 0) {
                return Result.error("盘点单【" + entity.getCode() + "】不能重复提交");
            }
        }
        countingService.submit(entity);
        return Result.ok("提交成功");
    }

    /**
     * 作废 盘点单
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "作废 盘点单", notes = "作废 盘点单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping(value = "/invalid/{code}")
    public Result invalid(@PathVariable String code, HttpServletRequest request) {
        if(StrUtil.isBlank(code)){
            return Result.error(TipConst.CODE_NOT_EMPTY);
        }
        int updateNum = countingService.invalid(code);
        if(updateNum == 0){
            return Result.error("盘点单号:" + code + "作废失败!");
        }else{
            return Result.ok("盘点单号:" + code + "作废成功!");
        }
    }

    /**
     * 获取 盘点单 详情
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 盘点单 详情", notes = "获取 盘点单 详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "盘点单code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = CountingVO.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result counting(@PathVariable String code,@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize, HttpServletRequest request) {
        try {
            CountingVO entity = countingService.getOneByCode(code,pageNum,pageSize,UserUtil.getBranchCode());
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 盘点登记 保存
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "盘点登记 保存", notes = "盘点登记 保存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PostMapping(value = "/register")
    public Result register(@RequestBody @Validated Counting entity, HttpServletRequest request) {
        if(StrUtil.isBlank(entity.getCode())){
            return Result.error(TipConst.CODE_NOT_EMPTY);
        }
        try {
            //TODO 检查批量更新保存是否有效
            countingService.updateRegisterByCode(entity);
            return Result.ok("盘点登记保存成功！");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }

    }

    /**
     * 盘点登记 提交
     * @param counting
     * @param request
     * @return
     */
    @ApiOperation(value = "盘点登记 提交", notes = "盘点登记 提交")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PutMapping(value = "/confirm")
    public Result confirm(@RequestBody @Validated Counting counting, HttpServletRequest request) {
        try {
            int updateNum = countingService.confirm(counting);
            if(updateNum == 0){
                return Result.error("提交失败!");
            }else{
                return Result.ok("提交成功!");
            }
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除 盘点单
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 盘点单", notes = "删除 盘点单", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            countingService.remove(codes);
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取 盘点单 打印 详情
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 盘点登记 详情", notes = "获取 盘点登记 详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "盘点单code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = CountingVO.class))
    @NeedLogin
    @GetMapping(value = "/registerDetail/{code}")
    public Result registerDetail(@PathVariable String code,@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize, HttpServletRequest request) {
        try {
            CountingVO entity = countingService.registerDetail(code,pageNum,pageSize);
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    @ApiOperation(value = "查询盘点库存", notes = "盘点时，根据条件查询要盘点的库存", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer ")
    })
    @NeedLogin
    @GetMapping(value = "/inventory")
    public Result listInventory(InventoryDTO inventoryDTO, HttpServletRequest request) {
        try {
            //校验授权仓库code和货主code不能为空
            Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            //登录账号授权的仓库过滤
            inventoryDTO.setWarehouseCodes(authMap.get(CommonConst.WAREHOUSE_CODES));
            //登录账号授权的货主过滤 盘点暂时不对货主进行过滤
//            inventoryDTO.setShipmentCodes(UserUtil.getAuthorizeShipmentCodes());
            inventoryDTO.setGroupCode(UserUtil.getBranchCode());
            InventoryVO inventoryVoSum = inventoryService.queryListSum(inventoryDTO);
            List<InventoryVO> inventoryVOList = inventoryService.queryList(inventoryDTO);
            Page returnPage = new Page(inventoryDTO.getPageNum(),inventoryDTO.getPageSize());
            returnPage.setRecords(inventoryVOList);
            returnPage.setTotal(inventoryVoSum.getTotal());
            returnPage.setSumObject(inventoryVoSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


 }
